package org.jeecgframework.web.controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.metal.OceanTheme;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.DataintegritycheckServiceI;
import org.jeecgframework.web.system.pojo.base.DataintegritycheckEntity;
import org.jeecgframework.web.system.pojo.base.ZyEmailEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import freemarker.template.Configuration;
import freemarker.template.Template;



/**   
 * @Title: Controller
 * @Description: 数据一致性检查
 * @author onlineGenerator
 * @date 2016-07-04 10:27:11
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/dataintegritycheckController")
public class DataintegritycheckController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(DataintegritycheckController.class);

	@Autowired
	private DataintegritycheckServiceI dataintegritycheckService;
	@Autowired
	private SystemService systemService;
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 数据一致性检查列表 页面跳转
	 * @return
	 */
	@RequestMapping(params = "dataintegritycheck")
	public ModelAndView dataintegritycheck(HttpServletRequest request) {
		return new ModelAndView("com/zybk/dataintegritycheck/dataintegritycheckList");
	}

	/**
	 * easyui AJAX请求数据
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(DataintegritycheckEntity dataintegritycheck,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(DataintegritycheckEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, dataintegritycheck, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.dataintegritycheckService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * @author xiul
	 * 2016-7-5 下午2:24:08
	 * Description 执行sql 
	 */
	@RequestMapping(params = "executeSql")
	public ModelAndView executeSql(HttpServletRequest req) {
		List<Map<String, Object>> li = dataintegritycheckService.executeSql();
		req.setAttribute("li", li);
		return new ModelAndView("com/zybk/dataintegritycheck/executeSql");
	}
	
	/**
	 * @author xiul
	 * 2016-7-5 下午2:24:16
	 * Description 发送邮件 
	 */
	@ResponseBody
	@RequestMapping(params = "sendMail")
	public AjaxJson sendMail(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		boolean flag = true;
		message = "发送成功";
		try {
			String receiver = oConvertUtils.getString(request.getParameter("receiver"));
			if(!"".equals(receiver)){
				List<Map<String, Object>> li = dataintegritycheckService.executeSql();
				Map<String, Object> propMap = new HashMap<String, Object>();
				propMap.put("datas", li);
				Configuration freeMarkerConfig = null;
				Template template = null;
				freeMarkerConfig = new Configuration();
				freeMarkerConfig.setDirectoryForTemplateLoading(new File(SendMailUtil.getFilePath()));
				// 获取模板
				template = freeMarkerConfig.getTemplate("mail_DataintegrityCheck.ftl",new Locale("Zh_cn"), "UTF-8");
				// 模板内容转换为string
				String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, propMap);
//				String fileName = StaticValue.UPLOAD_PATH + DateUtils.date2Str(new Date(),DateUtils.date_sdf)+ ".html";
				String fileName = StaticValue.UPLOAD_PATH +"attach.html";
				File file = new File(fileName);
				if(file.exists()){
					file.delete();
				}
				file.createNewFile();
				FileWriter fw = new FileWriter(file);
				BufferedWriter bw = new BufferedWriter(fw);
				bw.write(htmlText);
				bw.close();
				System.err.println(file.getName());
				SendMailUtil.sendHTMLeMailWithAttach(receiver, "数据一致性检查结果", file);
			}
		} catch (Exception e) {
			message = "发送失败";
			flag = false;
			e.printStackTrace();
		}
		systemService.addLog(message, Globals.log_type_SEND_EMAIL, Globals.Log_Leavel_INFO);
		j.setMsg(message);
		j.setSuccess(flag);
		return j;
	}
	
	/**
	 * 数据一致性检查新增页面跳转
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(DataintegritycheckEntity dataintegritycheck, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(dataintegritycheck.getId())) {
			dataintegritycheck = dataintegritycheckService.getEntity(DataintegritycheckEntity.class, dataintegritycheck.getId());
			req.setAttribute("dataintegritycheckPage", dataintegritycheck);
		}
		return new ModelAndView("com/zybk/dataintegritycheck/dataintegritycheck-add");
	}

	/**
	 * 添加数据一致性检查
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(DataintegritycheckEntity dataintegritycheck, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "数据一致性检查添加成功";
		try{
			dataintegritycheckService.save(dataintegritycheck);
		}catch(Exception e){
			e.printStackTrace();
			message = "数据一致性检查添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 数据一致性检查编辑页面跳转
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(DataintegritycheckEntity dataintegritycheck, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(dataintegritycheck.getId())) {
			dataintegritycheck = dataintegritycheckService.getEntity(DataintegritycheckEntity.class, dataintegritycheck.getId());
			req.setAttribute("dataintegritycheckPage", dataintegritycheck);
		}
		return new ModelAndView("com/zybk/dataintegritycheck/dataintegritycheck-update");
	}
	
	/**
	 * 更新数据一致性检查
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(DataintegritycheckEntity dataintegritycheck, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "数据一致性检查更新成功";
		DataintegritycheckEntity t = dataintegritycheckService.get(DataintegritycheckEntity.class, dataintegritycheck.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(dataintegritycheck, t);
			dataintegritycheckService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "数据一致性检查更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	
	/**
	 * 删除数据一致性检查
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(DataintegritycheckEntity dataintegritycheck, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		dataintegritycheck = systemService.getEntity(DataintegritycheckEntity.class, dataintegritycheck.getId());
		message = "数据一致性检查删除成功";
		try{
			dataintegritycheckService.delete(dataintegritycheck);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "数据一致性检查删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除数据一致性检查
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "数据一致性检查删除成功";
		try{
			for(String id:ids.split(",")){
				DataintegritycheckEntity dataintegritycheck = systemService.getEntity(DataintegritycheckEntity.class, 
				id
				);
				dataintegritycheckService.delete(dataintegritycheck);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "数据一致性检查删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
}
